/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.rpc.setting;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.document.DocumentPreviewWayEnum;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.service.setting.MetaSystemSettingService;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@RpcSchema(schemaId = "systemSettingProviderService")
public class SystemSettingRpcServiceImpl implements SystemSettingRpcService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private MetaSystemSettingService systemSettingService;

    @Override
    public String findSettingValue(String code) {
        DynaBean valueBean = metaService.selectOne("JE_CORE_SETTING", ConditionsWrapper.builder()
                .eq("CODE", code));
        if (null == valueBean) {
            return null;
        }
        return valueBean.getStr("VALUE");
    }

    @Override
    public Map<String, String> requireAllSettingValue() {
        Map<String, String> map = new HashMap<>();
        List<DynaBean> settingList = metaService.select("JE_CORE_SETTING", null);
        for (DynaBean dynaBean : settingList) {
            map.put(dynaBean.getStr("CODE"), dynaBean.getStr("VALUE"));
        }
        return map;
    }

    @Override
    public void writeValues(String attribute, Map<String, String> values) {
        systemSettingService.reloadLoadSystemSetting();
    }

    @Override
    public void writeValue(String attribute, String key, String value) {
        systemSettingService.doWriteSettingValue(attribute,key,value);
    }

    @Override
    public void reloadSetting() {
        systemSettingService.reloadLoadSystemSetting();
    }

    @Override
    public boolean isSaas() {
        return false;
    }

    @Override
    public String requirePlanProduct(String plan) {
        List<DynaBean> planBeanList = metaService.select("JE_CORE_SETPLAN", ConditionsWrapper.builder()
                .eq("JE_SYS_PATHSCHEME", plan));
        List<String> productList = new ArrayList<>();
        for (DynaBean eachPlanBean : planBeanList) {
            if ("1".equals(eachPlanBean.getStr("SETPLAN_YESORNOUSED"))) {
                productList.add("ALL");
                break;
            }
            if (!Strings.isNullOrEmpty(eachPlanBean.getStr("JE_SYS_AVAILABLEPRODUCTS"))) {
                productList.addAll(Splitter.on(",").splitToList(eachPlanBean.getStr("JE_SYS_AVAILABLEPRODUCTS")));
            }
        }

        if (productList.contains("ALL")) {
            return "ALL";
        }

        return Joiner.on(",").join(productList);
    }

    @Override
    public DocumentPreviewWayEnum getDocumentPreviewWayByFileSuffix(String fileSuffix) {
        DynaBean dynaBean = metaService.selectOne("JE_CORE_SETTING",
                ConditionsWrapper.builder().eq("CODE", "JE_SYS_DOCUMENT_FORMAT_PREVIEW_SETTING"));
        String value = dynaBean.getStr("VALUE");
        if (StringUtil.isEmpty(value)) {
            return DocumentPreviewWayEnum.no;
        }
        JSONArray jsonArray = JSON.parseArray(value);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String type = jsonObject.getString("type");
            if ("Office".equals(type)) {
                String format = jsonObject.getString("format");
                if (Arrays.asList(format.split(",")).contains(fileSuffix)) {
                    return DocumentPreviewWayEnum.valueOf(jsonObject.getString("previewWay"));
                }
            }
        }
        return DocumentPreviewWayEnum.no;
    }

    @Override
    public boolean checkDocumentAdmin(String userId) {
        List<DynaBean> list = metaService.select("JE_CORE_SETTING", ConditionsWrapper.builder().eq("CODE","JE_SYS_DOCADMINID"));
        if(list == null || list.isEmpty()){
            return false;
        }
        for (DynaBean eachBean:list) {
            String value = eachBean.getStr("VALUE");
            if(!Strings.isNullOrEmpty(value) && value.contains(userId)){
                return true;
            }
        }
        return false;
    }

}
